package com.sdp.irrigation.server.netty.decode;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.sdp.irrigation.protocol.CommPackage;
import com.sdp.irrigation.utils.JsonUtils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class JsonMessageDecoder extends ByteToMessageDecoder {
	
	private static final Logger logger = LoggerFactory.getLogger(JsonMessageDecoder.class);
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		//ctx.close();
		logger.error("############解码Jt808MessageDecoder错误");
		super.exceptionCaught(ctx, cause);
	}
	
	public static void main(String[] args) {
		System.out.println(new Date().getTime());
		
		System.out.println(new Date(1742612546999L));
	}
	
	
	
	private boolean isCompleteJson(String json) {
		try {
			JsonUtils.parseBean(json, CommPackage.class); // 尝试解析 JSON
	        return true; // 解析成功，说明 JSON 完整
	    } catch (Exception e) {
	    	logger.error("json解析失败，msg：[{}], size: {}", json, json.length());
	        return false; // 解析失败，说明 JSON 不完整或格式错误
	    }
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		try {
			if (in.isReadable()) {
				// 读取字节数据
	            byte[] bytes = new byte[in.readableBytes()];
	            in.readBytes(bytes);
	            
	            // 将字节数组转换为 JSON 字符串
	            String jsonString = new String(bytes, "UTF-8");
//	            if (!StringUtils.isEmpty(jsonString) && jsonString.indexOf("11014039") >= 0) {
//					//11041100
//	            	logger.info(" data size: {}, decode解码: {}", bytes.length, jsonString);
//				}
	            
	            if (!StringUtils.isEmpty(jsonString) && isCompleteJson(jsonString)) {
	            	logger.info("data size: {}, 上行消息: {}", bytes.length, jsonString);
	            	out.add(jsonString);
	            	bytes = null;
				}
//	            CommPackage packageData = JsonUtils.parseBean(jsonString, CommPackage.class);
//				//LocalDateTime start = LocalDateTime.now();
//				if (packageData != null) {
//					//logger.debug("%%%%%%%%%netty解析时间：" + (LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() - start.toInstant(ZoneOffset.of("+8")).toEpochMilli()));
//					out.add(JSON.toJSONString(packageData));
//				}
			}
		} catch (Exception e) {
			StackTraceElement[] stacks = e.getStackTrace();
			logger.error("Decoder print error: [{}]", e.getMessage());
			for (StackTraceElement stackTraceElement : stacks) {
				logger.error(stackTraceElement.toString());
			}
			throw e;
		}
		
	}

}
